package com.efounder.util;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.GridLayout.Spec;
import android.widget.TextView;

import com.efounder.builder.base.data.EFRowSet;
import com.efounder.ospmobilelib.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GridGeneratorPact {
	private static final int MIN_ROW_HEIGHT = 50;
	private static final int TEXT_SIZE_PLAIN = 16;
	private Context context;
	private DisplayMetrics displayMetrics;
	private int tag = -1;// 标记属于第几列
	private String itemId;//点击事件跳转的id
	
	int keyCount = 0;
	final int SIZE = 15;

	// private int oneTextWidth;
	private int oneTextHeight;

	public GridGeneratorPact(Context context) {
		super();
		this.context = context;
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		displayMetrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(displayMetrics);

		// 1 获取一个字的宽度
		TextView plainTextView = new TextView(context);
		plainTextView.setTextSize(TEXT_SIZE_PLAIN);
		Paint paint = plainTextView.getPaint();
		Rect rect = new Rect();
		// 返回包围整个字符串的最小的一个Rect区域
		paint.getTextBounds("序", 0, 1, rect);
		// oneTextWidth = rect.width();
		oneTextHeight = rect.height();
	}

	/**
	 * 生成网格
	 * 
	 * @param rowSets
	 * @return
	 */
	public GridLayout generateGrid(List<EFRowSet> rowSets, int layoutWidthPX) {
		// rowSets = new ArrayList<EFRowSet>();
		// EFRowSet rowSet1 = new EFRowSet();
		// rowSet1.setValue("0", "收文编号");
		// rowSet1.setValue("1", "0");
		// rowSets.add(rowSet1);
		//
		// EFRowSet rowSet2 = new EFRowSet();
		// rowSet2.setValue("0", "来文日期");
		// rowSet2.setValue("1", "2016-4-20");
		// rowSets.add(rowSet2);
		//
		// EFRowSet rowSet3 = new EFRowSet();
		// rowSet3.setValue("0", "限办日期");
		// rowSet3.setValue("1", null);
		// rowSets.add(rowSet3);
		//
		// EFRowSet rowSet4 = new EFRowSet();
		// rowSet4.setValue("0", "文件标题");
		// rowSet4.setValue("1", "关于中国石化信息化技术管理体系规划设计咨询项目询比价会议的通知-test-test");
		// rowSets.add(rowSet4);
		// ---------------------------测试数据 结束------------------------------
		GridLayout gridLayout = new GridLayout(context);
		gridLayout.setOrientation(GridLayout.HORIZONTAL);
		gridLayout.setBackgroundColor(Color.GRAY);
		// gridLayout.setBackgroundColor(Color.WHITE);
		gridLayout.setPadding(0, 0, 1, 1);

		// XXX 列数？
		System.out.println("key的个数" + rowSets.get(0).getAttriMap().size());
		if (rowSets.get(0).getAttriMap().size() < 2) {
			keyCount = 0;
			return null;
		} else if(rowSets.get(0).getAttriMap().size() == 4){
			keyCount = 0;
			int columnCount = rowSets.get(0).getAttriMap().size() - 2;
			// -----{type=td,Self_RowSet=, 1=264,// 0=收文编号}
			gridLayout.setColumnCount(columnCount);

			for (EFRowSet rowSet : rowSets) {
				// grid 列数
				@SuppressWarnings("rawtypes")
				Map attrMap = rowSet.getAttriMap();

				// 列宽 list
				List<Integer> columnWidths = computeColumnWidths(columnCount,
						layoutWidthPX);
				// 行高
				int rowHeight = computeRowHeight(attrMap, columnWidths);
				// 如果返回的行高为20,为gridlayout增加一个空白的view背景为白色
				if (rowHeight == 30) {
					View view = new View(context);
					// 行设置，第一个为参数为第几行，默认可不设置，第二个参数为跨行数，没有则表示不跨行
					Spec rowsSpec = GridLayout.spec(GridLayout.UNDEFINED, 1);
					// 列设置，第一个为参数为第几列，默认可不设置，第二个参数为跨列数，没有则表示不跨行
					Spec colsSpec = GridLayout.spec(GridLayout.UNDEFINED, 2);
					GridLayout.LayoutParams params = new GridLayout.LayoutParams(
							rowsSpec, colsSpec);
					params.height = rowHeight;
					params.width = GridLayout.LayoutParams.MATCH_PARENT;
					view.setLayoutParams(params);
					view.setBackgroundColor(context.getResources().getColor(
							R.color.white));
					gridLayout.addView(view);
				} else {

					// 生成table cell
					for (int i = 0; i < columnWidths.size(); i++) {
						tag = i;
						int columnWidth = columnWidths.get(i);
						// XXX key?
						String text = (String) attrMap.get("td" + i);
						// System.out.println("gridlayoout"+text);

						View cell = getTableCell(1, 1, columnWidth, rowHeight,
								text);
						gridLayout.addView(cell);
					}
				}
			}
			return gridLayout;
		}
		
		//如果含有15个key
		/*
		{maxlength=0, checked=false, required=false, alt=, submitflag=, regex=false, 
				closevalue=, title=二〇一四年信息中心第一批生产经营调整计划, _Self_RowSet=, name=Form, 
				value=type=1;id=d48a373b-9601-4e50-9e13-7bc565d4c0cf, message=, type=input,
				td0=签约依据, minlength=0}*/
		
		else if(rowSets.get(0).getAttriMap().size() == 15){
			keyCount = 15;
			int columnCount = 2;
			// -----{type=td,Self_RowSet=, 1=264,// 0=收文编号}
			gridLayout.setColumnCount(columnCount);

			for (EFRowSet rowSet : rowSets) {
				// grid 列数
				@SuppressWarnings("rawtypes")
				Map attrMap = rowSet.getAttriMap();

				// 列宽 list
				List<Integer> columnWidths = computeColumnWidths(columnCount,
						layoutWidthPX);
				// 行高
				int rowHeight = computeRowHeight(attrMap, columnWidths);
				// 如果返回的行高为20,为gridlayout增加一个空白的view背景为白色
				if (rowHeight == 30) {
					View view = new View(context);
					// 行设置，第一个为参数为第几行，默认可不设置，第二个参数为跨行数，没有则表示不跨行
					Spec rowsSpec = GridLayout.spec(GridLayout.UNDEFINED, 1);
					// 列设置，第一个为参数为第几列，默认可不设置，第二个参数为跨列数，没有则表示不跨行
					Spec colsSpec = GridLayout.spec(GridLayout.UNDEFINED, 2);
					GridLayout.LayoutParams params = new GridLayout.LayoutParams(
							rowsSpec, colsSpec);
					params.height = rowHeight;
					params.width = GridLayout.LayoutParams.MATCH_PARENT;
					view.setLayoutParams(params);
					view.setBackgroundColor(context.getResources().getColor(
							R.color.white));
					gridLayout.addView(view);
				} else {

					// 生成table cell
					for (int i = 0; i < columnWidths.size(); i++) {
						tag = i;
						int columnWidth = columnWidths.get(i);
						// XXX key?
						String text ="";
						
						if (keyCount == SIZE) {
							if (i == 0) {
								 text = (String) attrMap.get("td" +0);
							}else if (i == 1) {
								text = (String) attrMap.get("title");
								itemId = (String) attrMap.get("id");
							}
						}
						else {
							text = (String) attrMap.get("td" + i);
						}
						// System.out.println("gridlayoout"+text);

						View cell = getTableCell(1, 1, columnWidth, rowHeight,
								text);
						gridLayout.addView(cell);
					}
				}
			}
			return gridLayout;
		}
		return gridLayout;
		

	}

	private View getTableCell(int rowSpan, int colSpan, int width, int height,
			String cellText) {
		View cellView = null;
		// 行设置，第一个为参数为第几行，默认可不设置，第二个参数为跨行数，没有则表示不跨行
		Spec rowsSpec = GridLayout.spec(GridLayout.UNDEFINED, rowSpan);
		// 列设置，第一个为参数为第几列，默认可不设置，第二个参数为跨列数，没有则表示不跨行
		Spec colsSpec = GridLayout.spec(GridLayout.UNDEFINED, colSpan);
		GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowsSpec,
				colsSpec);
		params.width = width;
		params.height = height;
		params.leftMargin = 1;
		params.topMargin = 1;
		params.setGravity(Gravity.FILL);

		// 创建TextView
		TextView textView = new TextView(context);
		textView.setLayoutParams(params);
		textView.setBackgroundColor(Color.WHITE);
		textView.setGravity(Gravity.CENTER);
		textView.setTextSize(TEXT_SIZE_PLAIN);
		textView.setText(cellText);
		textView.setTextColor(Color.BLACK);
		
		if (keyCount == SIZE) {
			textView.setTextColor(Color.BLUE);
			textView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//XXX 跳转
				System.out.println("点击事件");
				System.out.println(itemId);
				
					
				}
			});
		}
		System.out.println("colSpan" + colSpan);
		if (tag == 0) {
			textView.setBackgroundColor(context.getResources().getColor(
					R.color.billdetail_form1));
		} else if (tag == 1) {
			textView.setBackgroundColor(context.getResources().getColor(
					R.color.billdetail_form2));
		}
		cellView = textView;
		return cellView;
	}

	private static List<Integer> computeColumnWidths(int columnCount,
			int layoutWidthPX) {
		List<Integer> columnWidths = new ArrayList<Integer>();
		if (columnCount == 1) {// 1列的情况
			columnWidths.add(layoutWidthPX);
		} else if (columnCount == 2) {// 2列的情况
			int columnWidth1 = layoutWidthPX / 3;
			int columnWidth2 = layoutWidthPX / 3 * 2;
			columnWidths.add(columnWidth1);
			columnWidths.add(columnWidth2);
		}

		return columnWidths;
	}

	/**
	 * 根据文字多少和列宽，计算列高
	 * 
	 * @param attrMap
	 * @param columnWidths
	 * @return
	 */
	private int computeRowHeight(@SuppressWarnings("rawtypes") Map attrMap,
			List<Integer> columnWidths) {
		int maxRowHeight = 0;
		int oneRowHeight = oneTextHeight * 2;// (int)(ONE_ROW_HEIGHT_PX *
												// displayMetrics.density);
		for (int i = 0; i < columnWidths.size(); i++) {
	System.out.println("columnWidths.size():"+columnWidths.size());
			int columnWidth = columnWidths.get(i);
			String text ="1";
			if (keyCount == SIZE) {
				if (i  == 0 ) {
					 text = (String) attrMap.get("td" + 0);
				}else if(i == 1) {
					 text = (String) attrMap.get("title");
					 System.out.println("title279:"+text);
				}
			}else{
			// XXX key?
			 text = (String) attrMap.get("td" + i);
			// 得到第一列里面的字，如果为空，这一行的高度设置为空
			String text1 = (String) attrMap.get("td" + 0);
			text1 = (text1 == null ? "" : text1);
			// 如果 text为空 返回的高度是0
			if (text1 == "") {
				return 30;
			}}
			
			// 测量文字宽度
			TextView plainTextView = new TextView(context);
			plainTextView.setTextSize(TEXT_SIZE_PLAIN);
			Paint paint = plainTextView.getPaint();
			System.out.println(text+"292");
			float textWidth = paint.measureText(text) + 6;
			int rowCount = (int) Math.ceil(textWidth / columnWidth);
			int rowHeight = rowCount * oneRowHeight;
			if (rowHeight > maxRowHeight) {
				maxRowHeight = rowHeight;
			}
		}
		if (maxRowHeight < MIN_ROW_HEIGHT) {
			maxRowHeight = (int) (MIN_ROW_HEIGHT * displayMetrics.density);
		} else {
			maxRowHeight = maxRowHeight + (int) (10 * displayMetrics.density)
					* 2;
		}

		return maxRowHeight;
	}
}
